﻿using System.Collections.Generic;
using System.Text;

namespace Twitter
{
    public class PlainTextMessageBuilder : IMessageBuilder
    {
        StringBuilder appendedFragments;
        private int twitterMaxCharCountPerMessage;

        private const int DefaultTwitterMaxCharCountPerMessage = 110;        
        private const string ellipsisString = " ...";

        public PlainTextMessageBuilder()
            : this(DefaultTwitterMaxCharCountPerMessage)
        {
        }

        public PlainTextMessageBuilder(int twitterMaxCharCountPerMessage)
        {
            this.appendedFragments = new StringBuilder();
            this.twitterMaxCharCountPerMessage = twitterMaxCharCountPerMessage;
        }

        public int TwitterMaxCharCountPerMessage
        {
            get { return twitterMaxCharCountPerMessage; }
        }

        public int SplittedMessageLength
        {
            get { return TwitterMaxCharCountPerMessage - ellipsisString.Length; }
        }

        #region IMessageBuilder Members

        public void Clear()
        {
            appendedFragments = new StringBuilder();
        }

        public void AppendFragment(string fragment)
        {
            appendedFragments.Append(fragment);            
        }

        public IEnumerable<string> GetMessages()
        {
            if (appendedFragments.Length == 0)
                yield break;

            string message = appendedFragments.ToString();

            int currentMessageStartOffset = 0;

            while (currentMessageStartOffset < message.Length - twitterMaxCharCountPerMessage)
            {
                yield return string.Format("{0}{1}",
                    message.Substring(currentMessageStartOffset, SplittedMessageLength),
                    ellipsisString);

                currentMessageStartOffset += SplittedMessageLength;
            }

            yield return message.Substring(currentMessageStartOffset);            
        }

        #endregion
    }
}
